<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <el-card class="conversation-list">
      <el-scrollbar>
        <el-menu :default-active="activeConversationId" @select="loadMessages">
          <el-menu-item
            v-for="conv in conversations"
            :key="conv.id"
            :index="conv.id.toString()"
          >
            {{ conv.title }}
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
      <el-button type="primary" @click="createConversation" class="mt-2" block>
        新建对话
      </el-button>
    </el-card>

    <!-- 右侧聊天窗口 -->
    <div class="chat-box">
      <el-card class="messages" ref="messageBox">
        <div
          v-for="msg in messages"
          :key="msg.id"
          class="message-item"
          :class="msg.role"
        >
          <div class="avatar">
            <el-avatar v-if="msg.role === 'user'" icon="User" />
            <el-avatar v-else icon="Cpu" />
          </div>
          <div class="content">
            <el-card shadow="hover">{{ msg.content }}</el-card>
          </div>
        </div>
      </el-card>

      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          placeholder="请输入你的问题..."
          :rows="2"
          @keyup.enter.native="sendStreamMessage"
        />
        <el-button type="primary" @click="sendStreamMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { tr } from "element-plus/es/locales.mjs";

const conversations = ref([]);
const messages = ref([]);
const activeConversationId = ref(null);
const inputMessage = ref("");
const messageBox = ref(null);

const scrollToBottom = () => {
  nextTick(() => {
    if (messageBox.value) {
      messageBox.value.scrollTop = messageBox.value.scrollHeight;
    }
  });
};

// 获取会话列表
const loadConversations = async () => {
  try {
    const res = await axios.get("http://192.168.2.13:8081/ai/chat/conversation/list", {
      params: { userId: 1 },
    });
    conversations.value = res.data;
    if (conversations.value.length > 0) {
      activeConversationId.value = conversations.value[0].id;
      await loadMessages(activeConversationId.value);
    }
  } catch {
    ElMessage.error("加载会话失败");
  }
};

// 获取消息
const loadMessages = async (conversationId) => {
  activeConversationId.value = conversationId;
  try {
    const res = await axios.get("http://192.168.2.13:8081/ai/chat/conversation/history", {
      params: { conversationId },
    });
    messages.value = res.data;
    scrollToBottom();
  } catch {
    ElMessage.error("加载消息失败");
  }
};

// 新建会话
const createConversation = async () => {
  try {
    const res = await axios.post("http://192.168.2.13:8081/ai/chat/conversation/create", {
      userId: 1,
      title: "新的对话",
      model: "deepseek-chat",
      modelId: 1,
      pinned: false,
      roleId: 1,
      maxTokens: 2048,
      maxContexts:10,
      temperature: 0.3,
    });
    conversations.value.unshift(res.data.data);
    activeConversationId.value = res.data.data.id;
    messages.value = [];
  } catch {
    ElMessage.error("新建会话失败");
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return ElMessage.warning("请输入内容");
  }

  const userMsg = {
    role: "user",
    content: inputMessage.value,
  };
  messages.value.push(userMsg);
  scrollToBottom();

  const tempInput = inputMessage.value;
  inputMessage.value = "";

  try {
    const res = await axios.post("http://192.168.2.13:8081/ai/chat/conversation/send", {
      conversationId: activeConversationId.value,
      userId: 1,
      content: tempInput,
      useContext:true,
    });
    const aiMsg = {
      role: "assistant",
      content: res.data.receive.content,
    };
    messages.value.push(aiMsg);
    scrollToBottom();
  } catch {
    ElMessage.error("发送失败");
  }
};
// 发送消息（流式版）
const sendStreamMessage = async () => {
  if (!inputMessage.value.trim()) {
    return ElMessage.warning("请输入内容");
  }
  
  // 先插入用户消息
  const userMsg = {
    role: "user",
    content: inputMessage.value,
  };
  messages.value.push(userMsg);
  scrollToBottom();

  const tempInput = inputMessage.value;
  inputMessage.value = "";
  // 然后调用流式接口
  const response = await fetch("http://192.168.2.13:8081/ai/chat/conversation/sendStream", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      conversationId: activeConversationId.value,
      userId: 1,
      content: tempInput,
      useContext:true,
    }),
  });

  const reader = response.body.getReader();
  let decoder = new TextDecoder("utf-8");
  let aiReply = { role: "assistant", content: "" };
  messages.value.push(aiReply);
  scrollToBottom();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    // console.log("Received chunk", { done, value });
    // aiReply.content += decoder.decode(value, { stream: true });
     // 解码并拼接数据
    const text = decoder.decode(value, { stream: true });
    const chunks = text.split("\n");  // 每一行是一个数据块
    debugger
    for (let chunk of chunks) {
      if (chunk.startsWith("data:")) {
        // 解析出 `data: {}` 中的内容
        const data = chunk.slice(5).trim();
        if (data && data !== "[DONE]") {
          try {
            const messageData = JSON.parse(data);
            
            // 根据消息类型，决定是用户消息还是 AI 回复
            if (messageData.receive && messageData.receive.content) {
                            // 每次接收到新的内容时拼接并更新 aiReply
              aiReply.content += messageData.receive.content;
              
              // 强制 Vue 更新
              const updatedReply = { ...aiReply }; // 通过解构创建新对象，确保 Vue 侦测到更新
              messages.value = [...messages.value]; // 强制更新消息数组
              scrollToBottom(); // 滚动到最新消息
            }
          } catch (error) {
            console.error("解析流数据时出错：", error);
          }
        }
      }
    }
  }
};



onMounted(() => {
  loadConversations();
});
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  box-sizing: border-box;
}
.conversation-list {
  width: 250px;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
}
.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
}
.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.message-item.user {
  flex-direction: row-reverse;
  text-align: right;
}
.content {
  max-width: 70%;
}
.input-area {
  display: flex;
  gap: 12px;
  align-items: center;
}
</style>
